﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel;

namespace VideoSeller.Core.Configuration
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
		private readonly IKernel _kernel;

		public WindsorControllerFactory(IKernel kernel)
		{
			this._kernel = kernel;
		}

		public override void ReleaseController(IController controller)
		{
			_kernel.ReleaseComponent(controller);
		}

		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			if (controllerType == null)
			{
                return null;
				var errorMessage = string.Format("The controller for path '{0}' could not be found or doesn't implement IController.", requestContext.HttpContext.Request.Path);
				throw new HttpException(404, errorMessage);
			}

			return (IController)_kernel.Resolve(controllerType);
		}
    }
}